<script setup>
  import { reactive, ref, onMounted } from 'vue';
  import { useAdminStore } from '@/store';
  import { useTagStore } from '@/store';
  import { useRouter, useRoute } from 'vue-router';

  import useLoading from '@/hooks/loading';
  import tool from '@/utils/tool';
  import VerifyCode from '@cps/verify-code/index.vue';
  import { apiSetting } from '@/api/common';
  import SlidePuzzleVerify from '@/components/verify/slide-puzzle/index.vue';
  import SlideVerifyImg1 from '@/assets/verify/slide-puzzle1.png';
  import SlideVerifyImg2 from '@/assets/verify/slide-puzzle2.png';
  import SlideVerifyImg3 from '@/assets/verify/slide-puzzle3.png';
  import SlideVerifyImg4 from '@/assets/verify/slide-puzzle4.png';
  import SlideVerifyImg5 from '@/assets/verify/slide-puzzle5.png';

  const router = useRouter();
  const route  = useRoute();
  const verifyRef = ref(null);
  const { loading, setLoading } = useLoading(false);
  
  // const isDevelop = import.meta.env.VITE_APP_ENV === 'development';
  const openVerifyCode = false;

  const adminStore = useAdminStore();
  const loginConfig = tool.local.get('login-config');
  const formData = reactive({
    username: loginConfig?.username,
    password: loginConfig?.password,
    remember: loginConfig?.rememberPassword,
    verify_code: '',
  });
  const redirect = route.query.redirect ? route.query.redirect : '/';

  // 滑动拼图验证
  const sliderImgs = [
    SlideVerifyImg1,
    SlideVerifyImg2,
    SlideVerifyImg3,
    SlideVerifyImg4,
    SlideVerifyImg5,
  ];
  const slideVerifyVisible = ref(false);
  const disabledSubmit = ref(true);

  const handleSubmit = async ({values, errors}) => {
    if (loading.value) {
      return;
    }
    setLoading(true);
    if ((!openVerifyCode || verifyRef.value.checkResult(form.verify_code)) && !errors) {
      const result = await adminStore.login(formData);
      if (!result) {
        setLoading(false);
        return;
      }
      tool.local.set('login-config', {
        rememberPassword: true,
        username: formData.username,
        password: formData.password,
      });
      // useTagStore().clearTags();
      router.push(redirect);
    }
    setLoading(false);
  }

  // 设置
  const setting = async () => {
    const { data } = await apiSetting();
    if (data.login_bg_url) {
      document.getElementById('background').style.backgroundImage = `url(${data.login_bg_url})`;
    }
  };

  const handleSlideVerify = () => {
    slideVerifyVisible.value = true;
  };
  const verifySuccess = (times) => {
    // const msg = `验证成功, 耗时${(times / 1000).toFixed(1)}s`;
    // Message.success(msg);
    slideVerifyVisible.value = false;
    disabledSubmit.value = false;
  };
  const verifyFail = () => {
    // 验证不通过
  };
  const verifyClose = () => {
    slideVerifyVisible.value = false;
  };

  onMounted(async () => {
    await setting();
  });
</script>

<template>
  <div id="background" class="fixed"></div>
  <div class="bg-backdrop-layout"></div>
  <div class="login-container">
    <div class="login-width md:w-10/12 w-11/12 mx-auto flex justify-between h-full items-center">
      <div class="w-6/12 mx-auto left-panel rounded-l pl-5 pr-5 hidden md:block">
        <div class="logo">
<!--          <img :src="`${$url}logo.svg`" width="45">-->
          <img src="@/assets/logo.svg" width="45">
          <span>{{ $title }}</span>
        </div>
        <div class="slogan flex justify-end"><span></span></div>
      </div>

      <div class="md:w-6/12 w-11/12 md:rounded-r mx-auto pl-5 pr-5 pb-10">
        <h2 class="mt-10 text-3xl pb-0 mb-10">{{ $t('sys.login.title') }}</h2>
        <a-form :model="formData" @submit="handleSubmit">
          <a-form-item field="username" :hide-label="true" :rules="[{ required: true, message: $t('sys.login.usernameNotice') }]">
            <a-input
              v-model="formData.username"
              class="w-full"
              size="large"
              :placeholder="$t('sys.login.username')"
              allow-clear
            >
              <template #prefix><icon-user /></template>
            </a-input>
          </a-form-item>
          <a-form-item field="password" :hide-label="true" :rules="[{ required: true, message: $t('sys.login.passwordNotice') }]">
            <a-input-password
              v-model="formData.password"
              :placeholder="$t('sys.login.password')"
              size="large"
              allow-clear
            >
              <template #prefix><icon-lock /></template>
            </a-input-password>
          </a-form-item>
          <a-form-item
            v-if="openVerifyCode"
            field="verify_code"
            :hide-label="true"
            :rules="[{
              required: true,
              match: /^[a-zA-Z0-9]{4}$/,
              message: $t('sys.login.verifyCodeNotice')
            }]"
          >
            <a-input v-model="formData.verify_code" :placeholder="$t('sys.login.verifyCode')" size="large" allow-clear>
              <template #prefix><icon-safe /></template>
              <template #append>
                <verify-code ref="verifyRef" />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item hide-label>
            <a-button type="outline" long @click="handleSlideVerify"><icon-safe style="margin-right: 20px;"/>点击验证</a-button>
          </a-form-item>
          <div v-if="slideVerifyVisible === true">
            <slide-puzzle-verify
              ref="slideVerifyRef"
              :imgs="sliderImgs"
              @success="verifySuccess"
              @fail="verifyFail"
              @close="verifyClose"
            />
          </div>
          <a-form-item :hide-label="true" class="mt-5">
            <a-button html-type="submit" type="primary" long size="large" :disabled="disabledSubmit" :loading="loading">
              {{ $t('sys.login.loginBtn') }}
            </a-button>
          </a-form-item>

          <a-divider orientation="center">{{ $t('sys.login.otherLoginType') }}</a-divider>
          <div class="flex w-3/4 pt-2 mx-auto items-stretch justify-around">
            <a-avatar class="other-login wechat"><icon-wechat /></a-avatar>
            <a-avatar class="other-login alipay"><icon-alipay-circle /></a-avatar>
            <a-avatar class="other-login qq"><icon-qq /></a-avatar>
            <a-avatar class="other-login weibo"><icon-weibo /></a-avatar>
          </div>
        </a-form>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
  #background {
    top: 0; left: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
  }
  .bg-backdrop-layout {
    top: 0; left: 0;
    position: fixed;
    width: 100%; height: 100%;
    z-index: 2;
    backdrop-filter: blur(25px);
  }
  .login-container {
    width: 100%;
    height: 100%;
    position: absolute;
    background-size: cover;
    z-index: 3;
    .login-width {
      max-width: 950px;
      background: #fff;
      padding: 10px;
      height: 500px;
      position: relative;
      top: 50%;
      margin-top: -255px;
      border-radius: 10px;
    }
    .left-panel {
      height: 491px;
      background-image: url(@/assets/images/login_picture.svg);
      background-repeat: no-repeat;
      background-position: center 60px;
      background-size:contain;
    }
    .logo {
      display: flex; margin-top: 20px; color: #333;
      span {
        font-size: 28px; margin-left: 15px;
        color: rgb(var(--primary-6));
      }
    }
    .slogan {
      font-size: 16px; line-height: 50px;
    }
    :deep(.arco-input-append) {
      padding: 0 !important;
    }
    .other-login{
      cursor: pointer;
    }
    .qq:hover, .alipay:hover {
      background: #165DFF;
    }
    .wechat:hover {
      background: #0f9c02;
    }
    .weibo:hover {
      background: #f3ce2b;
    }
  }
</style>
